<?php
declare (strict_types = 1);
namespace App\Dao;

use App\Model\CouponLog;
use App\Utils\StringUtil;
class CouponLogDao
{
    use DaoTrait;

    public function __construct()
    {
        $this->driver=__CLASS__;    
    }   

    /**
     * 根据分页与条件查询数据
     * @Author czm
     * @DateTime 2020-05-26
     * @param array $map
     * @param array $page
     * @param array $fields
     * @return void
     */
    public function pageByWhere($map=[],$page=[],$fields=[],$scope=[]){
        $model=CouponLog::query();
        if(!empty($fields)){
            $model->select($fields);
        }
        $model=$model->with(['wxuser' => function ($query) {
            $query->select('openid', 'devicecode', 'nickname');
        }, 'coupon' => function ($query) {
            $query->select('id', 'unique_num');
        }])->when(!empty($map),function($query) use($map){
            $query->where($map);
        });
        $nickname=$scope['nickname']??'';
        $type=$scope['type']??'';
        $unique_num=$scope['unique_num']??'';
        $model = $model->OfNickName($nickname);
        $model = $model->OfEqField('type', $type);
        $model = $model->OfCoupon('unique_num', $unique_num);
        $count=$model->count();
        $data=$model->orderBy('id', 'desc')->paginate(intval($page['pageSize']),['*'],'page',$page['page'])->each(function ($value) {
            $wxuser = $value->wxuser;
            $coupon = $value->coupon;
            $value->forceFill([
                'nickname' => make(StringUtil::class)->strIsBase64($wxuser['nickname'] ?? ""),
                'devicecode' => $wxuser['openid'] ?? "",
                'unique_num' => $coupon['unique_num'] ?? "",
                'end_time' => date('Y-m-d H:i:s', $value->start_time) . '-' . date('Y-m-d H:i:s', $value->end_time),
            ]);
            $value->append(['type_explain_mapping', 'type_mapping'])->makeHidden(['wxuser', 'coupon']);
        })->toArray();
        return compact('count','data');
    }

    /**
     * 新建
     * @param $insertArray
     * @return int
     */
    public function add($insertArray){
        return CouponLog::query()->insertGetId($insertArray);

    }

    
    /**
   * 优惠券记录导出
   * @Author czm
   * @DateTime 2020-06-04
   * @param [type] $start_time
   * @param [type] $end_time
   * @return string 
   */
  public function outputLog($map=[],$head=[]){
    $this->deleteExpiredFile();
    $file_name = $this->getUniqueName().'.csv';
    $file_dir = BASE_PATH .$this->getFileDir(). '/'.$file_name;;
    if(!file_exists($file_dir)){
        touch($file_dir);
    }
    // 打开PHP文件句柄，php://output 表示直接输出到浏览器
    $fp = fopen($file_dir, 'ab');
    foreach ($head as $i => $v) {
        // CSV的Excel支持GBK编码，一定要转换，否则乱码
        $head[$i] =iconv("utf-8","gb2312//IGNORE",$v);
    }
    fputcsv($fp, $head);

    $lock=true;
    $model=CouponLog::query();
    $nickname=$map['nickname']??'';
    $type=$map['type']??'';
    $unique_num=$map['unique_num']??'';
    $model = $model->OfNickName($nickname);
    $model = $model->OfEqField('type', $type);
    $model = $model->OfCoupon('unique_num', $unique_num);

    $model->when(!empty($map['where']), function ($query) use ($map) {
        $query->where($map['where']); })
        ->chunk(3000, function ($items) use ($fp,&$lock) {
        $lock=false;
        $items=$items->toArray();
        foreach ($items as $item) {
            unset($item['is_del']);
            isset($item['start_time'])&&$item['start_time']=date("Y-m-d h:i:s", (int)$item['start_time']);
            isset($item['end_time'])&&$item['end_time']=date("Y-m-d h:i:s", (int)$item['end_time']);
            $enum=array_unique(explode(',',$item['type_explain']));
            sort($enum);
            foreach($enum as &$val){
                switch($val){
                    case 1:$val='话费充值'; break;
                    case 2:$val='赠送好友'; break;
                    case 3:$val='抽奖'; break;
                    case 4:$val='好友赠送'; break;
                    case 5:$val='充值抵扣'; break;
                    case 6:$val='退款返还'; break;
                }
            }
            $item['type_explain']=implode("/",$enum);
            switch($item['type']){
                case 1:$val='获取'; break;
                case 2:$val='失去'; break;
                default:$val='';break;
            }
            $item['type']=$val;
            $data=[];
            foreach($item as $val){
                $data[]=strval(iconv("utf-8", "gb2312//IGNORE", " ".strval($val)." "));
            }
            fputcsv($fp, $data);
        }
        return true;
    });

    if($lock){
        $title=strval(iconv("utf-8", "gb2312//IGNORE", " " . strval("该条件暂无数据") . " "));
        fputcsv($fp, [ $title]);
    }

    fclose($fp);
    return $file_dir;
  }

}
